import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, DataSource, In } from 'typeorm';
import { CreateClassDto } from './dto/create-class.dto';
import { UpdateClassDto } from './dto/update-class.dto';
import { QueryClassDto } from './dto/query-class.dto';
import { ClassEntity } from './entities/class.entity';
import { StudentClassEntity } from '~/modules/admin/manage/student/entities/student-class.entity';
import { StudentEntity } from '~/modules/admin/manage/student/entities/student.entity';
import { paginate } from '~/helper/paginate';
import { format, startOfWeek, endOfWeek, startOfMonth, endOfMonth, startOfQuarter, endOfQuarter, isBefore, isAfter, differenceInDays } from 'date-fns';
import { ClassAttendanceStatisticsDto, AttendancePeriodStatisticsDto } from './dto/class-attendance-statistics.dto';
import { AddStudentsDto } from './dto/add-students.dto';

@Injectable()
export class ClassService {
  constructor(
    @InjectRepository(ClassEntity)
    private classRepository: Repository<ClassEntity>,
    @InjectRepository(StudentClassEntity)
    private studentClassRepository: Repository<StudentClassEntity>,
    @InjectRepository(StudentEntity)
    private studentRepository: Repository<StudentEntity>,
    private dataSource: DataSource,
  ) {}

  async create(createClassDto: CreateClassDto) {
    // 从DTO中提取学生ID列表
    const { studentIds, selectedStudents, ...classData } = createClassDto;
    
    // 合并学生ID列表，优先使用selectedStudents
    const combinedStudentIds = selectedStudents || studentIds || [];
    
    console.log(`收到创建班级请求: ${JSON.stringify(classData)}`);
    console.log(`前端提供的学生ID: selectedStudents=${JSON.stringify(selectedStudents)}, studentIds=${JSON.stringify(studentIds)}`);
    console.log(`最终使用的学生ID: ${JSON.stringify(combinedStudentIds)}`);
    
    // 检查是否已存在相同的班级ID
    const existedClass = await this.classRepository.findOne({
      where: { classId: classData.classId },
    });

    if (existedClass) {
      throw new BadRequestException(`班级ID '${classData.classId}' 已存在`);
    }

    // 创建新班级
    const classEntity = this.classRepository.create(classData);
    const savedClass = await this.classRepository.save(classEntity);
    
    console.log(`班级创建成功: ${savedClass.classId}, ID: ${savedClass.id}`);
    
    // 如果提供了学生ID列表，创建班级和学生的关联
    if (combinedStudentIds.length > 0) {
      try {
        console.log(`尝试将学生关联到班级, 学生IDs: ${JSON.stringify(combinedStudentIds)}`);
        
        // 验证学生是否存在
        const studentEntities = await this.studentRepository.findBy({ 
          id: In(combinedStudentIds),
          isDelete: 0 
        });
        
        console.log(`找到有效学生: ${JSON.stringify(studentEntities.map(s => ({ id: s.id, name: s.userName })))}`);
        
        // 获取有效的学生ID
        const validStudentIds = studentEntities.map(student => student.id);
        
        if (validStudentIds.length !== combinedStudentIds.length) {
          console.warn(`有${combinedStudentIds.length - validStudentIds.length}个学生ID无效, 有效IDs: ${validStudentIds.join(', ')}`);
        }
        
        // 创建学生班级关联记录
        const studentClassEntities = validStudentIds.map(studentId => ({
          studentId,
          classId: savedClass.id,
          isDelete: 0,
          joinAt: new Date()
        }));
        
        if (studentClassEntities.length > 0) {
          const savedRelations = await this.studentClassRepository.save(studentClassEntities);
          console.log(`成功将${studentClassEntities.length}个学生添加到班级${savedClass.classId}, 关联IDs: ${savedRelations.map(r => r.id).join(', ')}`);
        }
      } catch (error) {
        console.error('添加学生到班级时出错:', error);
        // 不抛出异常，因为班级已创建成功，学生关联失败不应导致整个创建过程失败
      }
    }
    
    return savedClass;
  }

  async findAll(queryDto?: QueryClassDto) {
    const { page = 1, pageSize = 10, classId, className, classGrade, status } = queryDto || {};

    const queryBuilder = this.classRepository.createQueryBuilder('class');

    if (classId) {
      queryBuilder.andWhere('class.classId LIKE :classId', { classId: `%${classId}%` });
    }

    if (className) {
      queryBuilder.andWhere('class.className LIKE :className', { className: `%${className}%` });
    }

    if (classGrade !== undefined) {
      queryBuilder.andWhere('class.classGrade = :classGrade', { classGrade });
    }

    if (status !== undefined) {
      queryBuilder.andWhere('class.status = :status', { status });
    }

    // 设置默认排序
    queryBuilder.orderBy('class.createdAt', 'DESC');

    // 获取分页结果
    const paginationResult = await paginate(queryBuilder, { page, pageSize });

    // 获取每个班级的学生数量和学习进度
    const classesWithDetails = await Promise.all(
      paginationResult.items.map(async (classItem) => {
        // 直接使用数据库ID进行关联查询
        console.log(`查询班级${classItem.classId}的学生数量, 数据库ID为: ${classItem.id}, 类型: ${typeof classItem.id}`);
        
        const studentCount = await this.studentClassRepository.count({
          where: { classId: classItem.id, isDelete: 0 }
        });

        console.log(`班级${classItem.classId}(ID:${classItem.id})的学生数量: ${studentCount}`);

        // 计算学习进度 (基于学生打卡情况和学习计划)
        let progress = '未配置';
        
        // 只有设置了开始时间、结束时间和学习计划才计算进度
        if (classItem.startAt && classItem.expireAt && classItem.studyPlan) {
          try {
            const startDate = new Date(classItem.startAt);
            const endDate = new Date(classItem.expireAt);
            const currentDate = new Date();
            
            // 获取班级下所有学生的打卡记录总和
            const studentClassRecords = await this.studentClassRepository.find({
              where: { classId: classItem.id, isDelete: 0 }
            });
            
            console.log(`班级${classItem.classId}有${studentClassRecords.length}个学生记录`);
            
            // 获取学习计划数量（以逗号分隔的项目数量）
            const studyPlanItems = classItem.studyPlan ? classItem.studyPlan.split(',').filter(item => item.trim()).length : 0;
            console.log(`班级${classItem.classId}的学习计划有${studyPlanItems}个项目`);
            
            if (studentClassRecords.length > 0 && studyPlanItems > 0) {
              // 计算班级已开始的天数
              let passedDays = 0;
              if (currentDate <= startDate) {
                passedDays = 0;
              } else if (currentDate >= endDate) {
                // 如果已经结束，使用总天数
                passedDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
              } else {
                // 计算从开始到现在的天数
                passedDays = Math.ceil((currentDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
              }
              
              console.log(`班级${classItem.classId}已开始${passedDays}天`);
              
              // 理论上应该完成的打卡总次数 = 学生人数 × 学习计划项目数 × 已过天数
              const theoreticalCheckins = studentClassRecords.length * studyPlanItems * passedDays;
              
              // 实际完成的打卡总次数
              const actualCheckins = studentClassRecords.reduce((sum, record) => sum + (record.checkinDays || 0), 0);
              
              console.log(`班级${classItem.classId}理论应打卡${theoreticalCheckins}次，实际打卡${actualCheckins}次`);
              
              if (theoreticalCheckins > 0) {
                // 计算进度百分比
                const progressValue = Math.min(100, Math.floor((actualCheckins / theoreticalCheckins) * 100));
                progress = `${progressValue}%`;
                console.log(`班级${classItem.classId}的学习进度为${progress}`);
              } else {
                progress = '0%';
              }
            } else {
              progress = '0%';
              console.log(`班级${classItem.classId}无学生或学习计划为空，进度为0%`);
            }
          } catch (error) {
            console.error(`计算班级${classItem.classId}学习进度时出错:`, error);
            progress = '计算错误';
          }
        } else {
          console.log(`班级${classItem.classId}未配置完整的学习计划信息，无法计算学习进度`);
        }

        // 获取教师名称
        let teacherName = '未分配';
        if (classItem.classTeacher) {
          try {
            // 查询教师表获取教师姓名
            console.log(`尝试获取教师ID:${classItem.classTeacher}的姓名`);
            
            // 使用数据库查询获取教师姓名
            let teacherResult = await this.classRepository.query(
              'SELECT nickname FROM sys_user WHERE id = ?', 
              [classItem.classTeacher]
            );
            
            console.log('教师查询结果:', JSON.stringify(teacherResult));
            
            if (teacherResult && teacherResult.length > 0) {
              teacherName = teacherResult[0].nickname;
              console.log(`从数据库获取到教师${classItem.classTeacher}的姓名: ${teacherName}`);
            } else {
              teacherName = `教师${classItem.classTeacher}`;
              console.log(`未找到教师${classItem.classTeacher}的姓名记录，使用默认值`);
            }
          } catch (error) {
            console.error('获取教师名称失败', error);
            teacherName = `教师${classItem.classTeacher}`;
          }
        }

        return {
          ...classItem,
          studentCount,
          progress,
          teacherName,
        };
      })
    );

    return {
      items: classesWithDetails,
      meta: paginationResult.meta,
    };
  }

  async findOne(id: string) {
    const classEntity = await this.classRepository.findOne({
      where: { classId: id },
    });

    if (!classEntity) {
      throw new NotFoundException(`班级ID ${id} 不存在`);
    }

    // 获取班级学生数量 - 修复单个班级详情的学生统计
    console.log(`查询班级详情${classEntity.classId}的学生数量, 数据库ID为: ${classEntity.id}, 类型: ${typeof classEntity.id}`);

    // 查询该班级的所有学生关联记录
    const studentClassRecords = await this.studentClassRepository.find({
      where: { classId: classEntity.id, isDelete: 0 }
    });
    
    const studentCount = studentClassRecords.length;
    console.log(`班级详情: 班级${classEntity.classId}(ID:${classEntity.id})的学生数量: ${studentCount}`);

    // 计算学习进度
    let progress = '未配置';
    
    // 只有设置了开始时间、结束时间和学习计划才计算进度
    if (classEntity.startAt && classEntity.expireAt && classEntity.studyPlan) {
      try {
        const startDate = new Date(classEntity.startAt);
        const endDate = new Date(classEntity.expireAt);
        const currentDate = new Date();
        
        console.log(`班级${classEntity.classId}有${studentClassRecords.length}个学生记录`);
        
        // 获取学习计划数量（以逗号分隔的项目数量）
        const studyPlanItems = classEntity.studyPlan ? classEntity.studyPlan.split(',').filter(item => item.trim()).length : 0;
        console.log(`班级${classEntity.classId}的学习计划有${studyPlanItems}个项目`);
        
        if (studentClassRecords.length > 0 && studyPlanItems > 0) {
          // 计算班级已开始的天数
          let passedDays = 0;
          if (currentDate <= startDate) {
            passedDays = 0;
          } else if (currentDate >= endDate) {
            // 如果已经结束，使用总天数
            passedDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
          } else {
            // 计算从开始到现在的天数
            passedDays = Math.ceil((currentDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
          }
          
          console.log(`班级${classEntity.classId}已开始${passedDays}天`);
          
          // 理论上应该完成的打卡总次数 = 学生人数 × 学习计划项目数 × 已过天数
          const theoreticalCheckins = studentClassRecords.length * studyPlanItems * passedDays;
          
          // 实际完成的打卡总次数
          const actualCheckins = studentClassRecords.reduce((sum, record) => sum + (record.checkinDays || 0), 0);
          
          console.log(`班级${classEntity.classId}理论应打卡${theoreticalCheckins}次，实际打卡${actualCheckins}次`);
          
          if (theoreticalCheckins > 0) {
            // 计算进度百分比
            const progressValue = Math.min(100, Math.floor((actualCheckins / theoreticalCheckins) * 100));
            progress = `${progressValue}%`;
            console.log(`班级${classEntity.classId}的学习进度为${progress}`);
          } else {
            progress = '0%';
          }
        } else {
          progress = '0%';
          console.log(`班级${classEntity.classId}无学生或学习计划为空，进度为0%`);
        }
      } catch (error) {
        console.error(`计算班级${classEntity.classId}学习进度时出错:`, error);
        progress = '计算错误';
      }
    } else {
      console.log(`班级${classEntity.classId}未配置完整的学习计划信息，无法计算学习进度`);
    }

    // 获取教师名称
    let teacherName = '未分配';
    if (classEntity.classTeacher) {
      try {
        // 查询教师表获取教师姓名
        console.log(`尝试获取班级详情教师ID:${classEntity.classTeacher}的姓名`);
        
        let teacherResult = await this.classRepository.query(
          'SELECT nickname FROM sys_user WHERE id = ?', 
          [classEntity.classTeacher]
        );
        
        console.log('班级详情教师查询结果:', JSON.stringify(teacherResult));
        
        if (teacherResult && teacherResult.length > 0) {
          teacherName = teacherResult[0].nickname;
          console.log(`从数据库获取到班级详情教师${classEntity.classTeacher}的姓名: ${teacherName}`);
        } else {
          teacherName = `教师${classEntity.classTeacher}`;
          console.log(`未找到班级详情教师${classEntity.classTeacher}的姓名记录，使用默认值`);
        }
      } catch (error) {
        console.error('获取教师名称失败', error);
        teacherName = `教师${classEntity.classTeacher}`;
      }
    }

    // 获取学生详细信息列表
    let students = [];
    
    if (studentClassRecords.length > 0) {
      try {
        // 获取所有学生ID列表
        const studentIds = studentClassRecords.map(record => record.studentId);
        console.log(`开始查询学生详细信息，学生ID列表: ${studentIds.join(', ')}`);
        
        // 查询学生详细信息
        const studentEntities = await this.studentRepository.find({
          where: { 
            id: In(studentIds),
            isDelete: 0 
          }
        });
        
        // 计算每个学生的理论应打卡次数（每位学生的理论打卡率相同）
        let theoreticalPerStudentCheckins = 0;
        if (classEntity.startAt && classEntity.expireAt && classEntity.studyPlan) {
          const startDate = new Date(classEntity.startAt);
          const endDate = new Date(classEntity.expireAt);
          const currentDate = new Date();
          
          let passedDays = 0;
          if (currentDate <= startDate) {
            passedDays = 0;
          } else if (currentDate >= endDate) {
            passedDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
          } else {
            passedDays = Math.ceil((currentDate.getTime() - startDate.getTime()) / (1000 * 60 * 60 * 24));
          }
          
          const studyPlanItems = classEntity.studyPlan ? classEntity.studyPlan.split(',').filter(item => item.trim()).length : 0;
          theoreticalPerStudentCheckins = studyPlanItems * passedDays;
        }
        
        // 构建学生信息列表
        students = studentClassRecords.map(classRecord => {
          // 找到对应的学生详情
          const studentInfo = studentEntities.find(s => s.id === classRecord.studentId);
          
          // 计算学生的打卡率
          let checkinRate = '0%';
          if (theoreticalPerStudentCheckins > 0) {
            const rate = Math.min(100, Math.floor((classRecord.checkinDays / theoreticalPerStudentCheckins) * 100));
            checkinRate = `${rate}%`;
          }
          
          // 如果找到学生详情，返回完整信息，否则返回基本信息
          return studentInfo ? {
            id: studentInfo.id,
            studentId: studentInfo.studentId,
            phone: studentInfo.phone,
            userName: studentInfo.userName,
            checkinDays: classRecord.checkinDays || 0,
            lastCheckinAt: classRecord.lastCheckinAt,
            joinAt: classRecord.joinAt,
            checkinRate
          } : {
            id: classRecord.studentId,
            checkinDays: classRecord.checkinDays || 0,
            lastCheckinAt: classRecord.lastCheckinAt,
            joinAt: classRecord.joinAt,
            checkinRate
          };
        });
        
        console.log(`成功获取班级${classEntity.classId}的${students.length}个学生信息`);
      } catch (error) {
        console.error(`获取班级${classEntity.classId}学生信息时出错:`, error);
      }
    }

    return {
      ...classEntity,
      studentCount,
      progress,
      teacherName,
      students // 添加学生详细信息列表
    };
  }

  async update(id: string, updateClassDto: UpdateClassDto) {
    // 从DTO中提取学生ID列表
    const { studentIds, selectedStudents, ...classData } = updateClassDto;
    
    // 合并学生ID列表，优先使用selectedStudents
    const combinedStudentIds = selectedStudents || studentIds || [];
    
    console.log(`收到更新班级请求: ${id}, 更新数据: ${JSON.stringify(classData)}`);
    console.log(`前端提供的学生ID: selectedStudents=${JSON.stringify(selectedStudents)}, studentIds=${JSON.stringify(studentIds)}`);
    console.log(`最终使用的学生ID: ${JSON.stringify(combinedStudentIds)}`);
    
    // 检查要更新的班级是否存在
    const classEntity = await this.classRepository.findOne({
      where: { classId: id },
    });

    if (!classEntity) {
      throw new NotFoundException(`班级ID ${id} 不存在`);
    }

    // 如果要更新班级ID，检查新的班级ID是否已存在
    if (classData.classId && classData.classId !== id) {
      const existedClass = await this.classRepository.findOne({
        where: { classId: classData.classId },
      });

      if (existedClass) {
        throw new BadRequestException(`班级ID '${classData.classId}' 已存在`);
      }
    }
    
    // 应用更新
    Object.assign(classEntity, classData);

    // 保存更新后的班级信息
    const updatedClass = await this.classRepository.save(classEntity);
    
    // 如果提供了学生ID列表，更新班级和学生的关联
    if (combinedStudentIds.length > 0) {
      try {
        console.log(`尝试更新班级${updatedClass.classId}的学生关联, 学生IDs: ${JSON.stringify(combinedStudentIds)}`);
        
        // 验证学生是否存在
        const studentEntities = await this.studentRepository.findBy({ 
          id: In(combinedStudentIds),
          isDelete: 0 
        });
        
        console.log(`找到有效学生: ${JSON.stringify(studentEntities.map(s => ({ id: s.id, name: s.userName })))}`);
        
        // 获取有效的学生ID
        const validStudentIds = studentEntities.map(student => student.id);
        
        if (validStudentIds.length !== combinedStudentIds.length) {
          console.warn(`有${combinedStudentIds.length - validStudentIds.length}个学生ID无效, 有效IDs: ${validStudentIds.join(', ')}`);
        }
        
        // 删除现有的班级学生关联
        await this.studentClassRepository.delete({ classId: updatedClass.id });
        console.log(`已删除班级${updatedClass.classId}的现有学生关联`);
        
        // 创建新的学生班级关联记录
        const studentClassEntities = validStudentIds.map(studentId => ({
          studentId,
          classId: updatedClass.id,
          isDelete: 0,
          joinAt: new Date()
        }));
        
        if (studentClassEntities.length > 0) {
          const savedRelations = await this.studentClassRepository.save(studentClassEntities);
          console.log(`成功将${studentClassEntities.length}个学生更新到班级${updatedClass.classId}, 关联IDs: ${savedRelations.map(r => r.id).join(', ')}`);
        }
      } catch (error) {
        console.error('更新班级学生关联时出错:', error);
        // 不抛出异常，因为班级已更新成功，学生关联失败不应导致整个更新过程失败
      }
    } else {
      // 如果没有提供学生ID列表，但前端可能想清空所有学生关联
      console.log(`前端未提供学生ID，将删除班级${updatedClass.classId}的所有学生关联`);
      await this.studentClassRepository.delete({ classId: updatedClass.id });
    }

    // 返回更新后的班级信息，包括学生数量和学习进度
    return this.findOne(classData.classId || id);
  }

  async remove(id: string) {
    // 检查班级是否存在
    const classEntity = await this.classRepository.findOne({
      where: { classId: id },
    });

    if (!classEntity) {
      throw new NotFoundException(`班级ID ${id} 不存在`);
    }

    // 先删除该班级关联的学生班级记录
    await this.studentClassRepository.delete({ classId: classEntity.id });

    // 删除班级
    await this.classRepository.remove(classEntity);

    // 返回被删除的班级信息
    return { ...classEntity, deleted: true };
  }

  /**
   * 获取班级考勤统计数据
   * @param id 班级ID
   */
  async getClassAttendanceStatistics(id: string): Promise<ClassAttendanceStatisticsDto> {
    // 检查班级是否存在
    const classEntity = await this.classRepository.findOne({
      where: { classId: id },
    });

    if (!classEntity) {
      throw new NotFoundException(`班级ID ${id} 不存在`);
    }

    const now = new Date();
    
    // 定义各时间段
    const weekStart = startOfWeek(now, { weekStartsOn: 1 }); // 周一开始
    const weekEnd = endOfWeek(now, { weekStartsOn: 1 });
    
    const monthStart = startOfMonth(now);
    const monthEnd = endOfMonth(now);
    
    const quarterStart = startOfQuarter(now);
    const quarterEnd = endOfQuarter(now);
    
    try {
      // 获取班级中的所有学生
      const studentClassRecords = await this.studentClassRepository.find({
        where: { classId: classEntity.id, isDelete: 0 }
      });
      
      if (!studentClassRecords || studentClassRecords.length === 0) {
        return this.createEmptyClassStatistics(classEntity);
      }
      
      // 计算不同时间段的统计数据
      const totalStats = this.calculateClassPeriodStatistics(classEntity, studentClassRecords, null, null);
      const quarterStats = this.calculateClassPeriodStatistics(classEntity, studentClassRecords, quarterStart, quarterEnd);
      const monthStats = this.calculateClassPeriodStatistics(classEntity, studentClassRecords, monthStart, monthEnd);
      const weekStats = this.calculateClassPeriodStatistics(classEntity, studentClassRecords, weekStart, weekEnd);
      
      return {
        classId: classEntity.classId,
        className: classEntity.className,
        studentCount: studentClassRecords.length,
        total: totalStats,
        quarter: quarterStats,
        month: monthStats,
        week: weekStats
      };
    } catch (error) {
      console.error(`获取班级${id}考勤统计数据失败:`, error);
      return this.createEmptyClassStatistics(classEntity);
    }
  }
  
  /**
   * 创建空的班级统计数据对象
   */
  private createEmptyClassStatistics(classEntity: ClassEntity): ClassAttendanceStatisticsDto {
    const emptyPeriodStats: AttendancePeriodStatisticsDto = {
      actualCheckins: 0,
      theoreticalCheckins: 0,
      dailyAverageCheckins: 0,
      attendanceRate: '0%'
    };
    
    return {
      classId: classEntity.classId,
      className: classEntity.className,
      studentCount: 0,
      total: { ...emptyPeriodStats },
      quarter: { ...emptyPeriodStats },
      month: { ...emptyPeriodStats },
      week: { ...emptyPeriodStats }
    };
  }
  
  /**
   * 计算给定时间段内的班级考勤统计数据
   */
  private calculateClassPeriodStatistics(
    classEntity: ClassEntity,
    studentClassRecords: StudentClassEntity[],
    periodStart: Date | null,
    periodEnd: Date | null
  ): AttendancePeriodStatisticsDto {
    let actualCheckins = 0;
    let theoreticalCheckins = 0;
    const now = new Date();
    
    if (!classEntity.startAt || !classEntity.studyPlan) {
      return {
        actualCheckins: 0,
        theoreticalCheckins: 0,
        dailyAverageCheckins: 0,
        attendanceRate: '0%'
      };
    }
    
    const classStartDate = new Date(classEntity.startAt);
    
    // 筛选指定时间段内的记录
    const filteredRecords = studentClassRecords.filter(record => {
      // 如果未指定时间段，计算所有记录
      if (!periodStart || !periodEnd) return true;
      
      // 如果班级在指定时间段之后开始，或者没有打卡记录，则排除
      if (isAfter(classStartDate, periodEnd) || !record.lastCheckinAt) return false;
      
      // 如果学生最后打卡时间在时间段之前，则排除
      const lastCheckin = new Date(record.lastCheckinAt);
      if (isBefore(lastCheckin, periodStart)) return false;
      
      return true;
    });
    
    // 计算实际打卡次数
    actualCheckins = filteredRecords.reduce((sum, record) => sum + (record.checkinDays || 0), 0);
    
    // 计算时间段
    let startDate = classStartDate;
    let endDate = now;
    
    // 如果指定了时间段，调整计算范围
    if (periodStart && isAfter(periodStart, classStartDate)) {
      startDate = periodStart;
    }
    
    if (periodEnd) {
      endDate = periodEnd;
    }
    
    // 如果开始日期在结束日期之后，返回空数据
    if (isAfter(startDate, endDate)) {
      return {
        actualCheckins: 0,
        theoreticalCheckins: 0,
        dailyAverageCheckins: 0,
        attendanceRate: '0%'
      };
    }
    
    // 计算天数
    const daysDiff = differenceInDays(endDate, startDate) + 1;
    
    // 学习计划项目数
    const studyPlanItems = classEntity.studyPlan.split(',').filter(item => item.trim()).length;
    
    if (studyPlanItems === 0 || filteredRecords.length === 0) {
      return {
        actualCheckins: 0,
        theoreticalCheckins: 0,
        dailyAverageCheckins: 0,
        attendanceRate: '0%'
      };
    }
    
    // 班级理论应打卡次数 = 学生数 * 学习计划项目数 * 天数
    theoreticalCheckins = filteredRecords.length * studyPlanItems * daysDiff;
    
    // 计算日均打卡数
    const dailyAverageCheckins = daysDiff > 0 
      ? Math.round((actualCheckins / daysDiff) * 10) / 10 
      : 0;
    
    // 计算打卡率
    const attendanceRate = theoreticalCheckins > 0 
      ? Math.min(100, Math.round((actualCheckins / theoreticalCheckins) * 100)) 
      : 0;
    
    return {
      actualCheckins,
      theoreticalCheckins,
      dailyAverageCheckins,
      attendanceRate: `${attendanceRate}%`
    };
  }

  /**
   * 添加学生到班级
   * @param id 班级ID
   * @param addStudentsDto 包含学生ID列表的DTO
   */
  async addStudentsToClass(id: string, addStudentsDto: AddStudentsDto) {
    // 检查班级是否存在
    const classEntity = await this.classRepository.findOne({
      where: { classId: id },
    });

    if (!classEntity) {
      throw new NotFoundException(`班级ID ${id} 不存在`);
    }

    const { studentIds } = addStudentsDto;
    
    if (!studentIds || studentIds.length === 0) {
      throw new BadRequestException('学生ID列表不能为空');
    }

    try {
      console.log(`尝试添加学生到班级${classEntity.classId}, 学生IDs: ${JSON.stringify(studentIds)}`);
      
      // 验证学生是否存在
      const studentEntities = await this.studentRepository.findBy({ 
        id: In(studentIds),
        isDelete: 0 
      });
      
      console.log(`找到有效学生: ${JSON.stringify(studentEntities.map(s => ({ id: s.id, name: s.userName })))}`);
      
      // 获取有效的学生ID
      const validStudentIds = studentEntities.map(student => student.id);
      
      if (validStudentIds.length !== studentIds.length) {
        console.warn(`有${studentIds.length - validStudentIds.length}个学生ID无效, 有效IDs: ${validStudentIds.join(', ')}`);
      }
      
      if (validStudentIds.length === 0) {
        throw new BadRequestException('没有有效的学生ID');
      }
      
      // 获取当前班级已有的学生ID列表
      const existingStudentRecords = await this.studentClassRepository.find({
        where: { classId: classEntity.id, isDelete: 0 }
      });
      
      // 过滤出尚未添加到班级的学生ID
      const existingStudentIds = existingStudentRecords.map(record => record.studentId);
      const newStudentIds = validStudentIds.filter(id => !existingStudentIds.includes(id));
      
      // 如果所有学生都已在班级中，返回提示信息
      if (newStudentIds.length === 0) {
        return {
          message: '所有学生已在班级中',
          classId: classEntity.classId,
          className: classEntity.className,
          addedStudents: 0
        };
      }
      
      // 创建学生班级关联记录
      const studentClassEntities = newStudentIds.map(studentId => ({
        studentId,
        classId: classEntity.id,
        isDelete: 0,
        joinAt: new Date()
      }));
      
      // 保存学生班级关联记录
      const savedRelations = await this.studentClassRepository.save(studentClassEntities);
      console.log(`成功将${studentClassEntities.length}个学生添加到班级${classEntity.classId}, 关联IDs: ${savedRelations.map(r => r.id).join(', ')}`);
      
      return {
        message: '添加学生成功',
        classId: classEntity.classId,
        className: classEntity.className,
        addedStudents: savedRelations.length,
        studentIds: newStudentIds
      };
    } catch (error) {
      console.error('添加学生到班级时出错:', error);
      throw new BadRequestException(`添加学生到班级失败: ${error.message}`);
    }
  }
}